package com.info.zhiduoduo.admin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.model.formbean.project.ProjectListFormBean;
import com.info.zhiduoduo.admin.model.formbean.report.EditReasonsForOverdueFormBean;
import com.info.zhiduoduo.admin.model.formbean.report.ReportListFormBean;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.company.CompanyPayType;
import com.info.zhiduoduo.common.constants.invoice.InvoiceType;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.dto.account.TradeRecordBriefDto;
import com.info.zhiduoduo.repository.dto.company.CompanyTradeFlagDto;
import com.info.zhiduoduo.repository.dto.company.CompanyZhaoshangSubLedgerIncomingRecordDto;
import com.info.zhiduoduo.repository.dto.crowdsource.ContractorInvoicefDto;
import com.info.zhiduoduo.repository.dto.crowdsource.CrowdOfflinePayProjectListDto;
import com.info.zhiduoduo.repository.dto.crowdsource.CrowdsourceTradeRecordDto;
import com.info.zhiduoduo.repository.dto.crowdsource.TaxClearanceCertificateDto;
import com.info.zhiduoduo.repository.dto.maker.VerifyingMakerDto;
import com.info.zhiduoduo.repository.dto.partner.PartnerExpireDto;
import com.info.zhiduoduo.repository.dto.project.ProjectJiugeOfflinePayDto;
import com.info.zhiduoduo.repository.dto.report.CountDetailDto;
import com.info.zhiduoduo.repository.dto.report.FinishedInventoryCountDto;
import com.info.zhiduoduo.repository.dto.report.RealtimePendingItemDto;
import com.info.zhiduoduo.repository.dto.report.StatisticCountDto;
import com.info.zhiduoduo.repository.dto.report.UnfinishedInvoiceCountDto;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyEntrustFile;
import com.info.zhiduoduo.repository.entity.invoice.Invoice;
import com.info.zhiduoduo.repository.entity.invoice.InvoiceInventory;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.report.DailyReport;
import com.info.zhiduoduo.repository.entity.report.DailyReportDto;
import com.info.zhiduoduo.repository.entity.system.SystemManager;
import com.info.zhiduoduo.repository.entity.taxer.TaxerInvoice;
import com.info.zhiduoduo.repository.mapper.company.*;
import com.info.zhiduoduo.repository.mapper.crowdsource.ContractorInvoiceMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceTradeRecordMapper;
import com.info.zhiduoduo.repository.mapper.entrustmentproject.EntrustmentProjectMapper;
import com.info.zhiduoduo.repository.mapper.evaluate.EvaluateMapper;
import com.info.zhiduoduo.repository.mapper.invoice.InvoiceMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerAccountMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerRescissionApplyMapper;
import com.info.zhiduoduo.repository.mapper.order.TradeRecordMapper;
import com.info.zhiduoduo.repository.mapper.partner.*;
import com.info.zhiduoduo.repository.mapper.project.NonstandardProjectMapper;
import com.info.zhiduoduo.repository.mapper.report.DailyReportMapper;
import com.info.zhiduoduo.repository.mapper.report.ReportMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;

import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ReportService extends BaseService {

	@Resource
	InvoiceMapper invoiceMapper;
	@Resource
	TaxerInvoiceMapper taxerInvoiceMapper;
	@Resource
	ReportMapper reportMapper;
	@Resource
	EvaluateMapper evaluateMapper;
	@Resource
	DailyReportMapper dailyReportMapper;
	@Resource
	MakerRescissionApplyMapper makerRescissionApplyMapper;
	@Resource
	MakerAccountMapper makerAccountMapper;
	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Resource
	CompanyProjectMapper projectMapper;
	@Resource
	PartnerWithdrawMapper partnerWithdrawMapper;
	@Resource
	PartnerStudioWithdrawMapper partnerStudioWithdrawMapper;
	@Resource
	PartnerAccountMapper partnerAccountMapper;
	@Resource
	CompanyZhaoshangSubLedgerIncomingRecordMapper companyZhaoshangSubLedgerIncomingRecordMapper;
	@Resource
	TradeRecordMapper tradeRecordMapper;
	@Resource
	CrowdsourceTradeRecordMapper crowdsourceTradeRecordMapper;
	@Resource
	private ProjectService projectService;
	@Resource
	EnterpriseRefundMapper enterpriseRefundMapper;
	@Resource
	EntrustmentProjectMapper entrustmentProjectMapper;
	@Resource
	CompanyEntrustFileMapper companyEntrustFileMapper;
	@Resource
	NonstandardProjectMapper nonstandardProjectMapper;
	@Resource
	ContractorInvoiceMapper contractorInvoiceMapper;
	@Resource
	CompanyApplyMapper companyApplyMapper;

	@Resource
	CommonConfig commonConfig;

	public SmartResult<DailyReportDto> listReport(BaseSimpleFormBean<ReportListFormBean> formBean) {
		@Valid ReportListFormBean reqdata = formBean.getReqdata();
		Date from = reqdata.getFrom();
		Date to = reqdata.getTo();
		Page<DailyReportDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		dailyReportMapper.listReport(from, to);
		return SmartResult.ofPage(page);
	}

	public SmartResult<CountDetailDto> listUnfinishUntaxAcctInvoiceDetail() {
		Date finishDate = DateUtil.nowDate();
		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}
		int untaxAcctInvoiceDays = -commonConfig.getUntaxAcctInvoiceDays();
		int understockInvoiceAddtionDays = -commonConfig.getUnderstockInvoiceAddtionDays();
		int understockUntaxAcctInvoiceDays = untaxAcctInvoiceDays + understockInvoiceAddtionDays;
		Date untaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, untaxAcctInvoiceDays);
		Date understockUntaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, understockUntaxAcctInvoiceDays);
		List<CountDetailDto> list = reportMapper.listUnfinishUntaxAcctUnstandardInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate, finishDate);
		return SmartResult.success(list);
	}

	public SmartResult<CountDetailDto> listUnfinishTaxAcctInvoiceDetail() {
		Date finishDate = DateUtil.nowDate();
		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}
		int taxAcctInvoiceDays = -commonConfig.getTaxAcctInvoiceDays();
		int understockInvoiceAddtionDays = -commonConfig.getUnderstockInvoiceAddtionDays();
		int understockTaxAcctInvoiceDays = taxAcctInvoiceDays + understockInvoiceAddtionDays;
		Date taxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, taxAcctInvoiceDays);
		Date understockTaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, understockTaxAcctInvoiceDays);
		List<CountDetailDto> list = reportMapper.listUnfinishTaxAcctUnstandardInvoice(understockTaxAcctInvoiceStartDate, taxAcctInvoiceStartDate, finishDate);
		return SmartResult.success(list);
	}

	/**
	 * 编辑逾期理由
	 * @param formBean formbean
	 * @return success
	 */
	public SmartResult editReasonsForOverdue(BaseSimpleFormBean<EditReasonsForOverdueFormBean> formBean){
		if ( null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		EditReasonsForOverdueFormBean reqdata = formBean.getReqdata();
		if (0 == reqdata.getId() || 0 == reqdata.getType() || StringUtil.isEmpty(reqdata.getReasonsForOverdue())) {
			return errorParamSmartResult();
		}
		if (1 == reqdata.getType()) {
			//未开 发票
			Invoice invoice = new Invoice().selectById(reqdata.getId());
			if (null == invoice) {
				return smartResult(StatusMsg.StatusMsg_326);
			}
			invoice.setReasonsForOverdue(reqdata.getReasonsForOverdue());
			if (invoice.updateById()) {
				return smartResult();
			} else {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		} else if (2 == reqdata.getType()) {
			//未开智杰祱发票
			TaxerInvoice taxerInvoice = new TaxerInvoice().selectById(reqdata.getId());
			if (null == taxerInvoice) {
				return smartResult(StatusMsg.StatusMsg_326);
			}
			taxerInvoice.setReasonsForOverdue(reqdata.getReasonsForOverdue());
			if (taxerInvoice.updateById()) {
				return smartResult();
			} else {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		} else if (3 == reqdata.getType()) {
			//未审核企业
			CompanyAccount companyAccount = new CompanyAccount().selectById(reqdata.getId());
			if (null ==  companyAccount) {
				return smartResult(StatusMsg.StatusMsg_315);
			}
			companyAccount.setReasonsForOverdue(reqdata.getReasonsForOverdue());
			if (companyAccount.updateById()) {
				return smartResult();
			} else {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		} else if (4 == reqdata.getType() || 5 == reqdata.getType()) {
			//未审核创客 未开工商户
			MakerAccount makerAccount = new MakerAccount().selectById(reqdata.getId());
			if (null ==  makerAccount) {
				return smartResult(StatusMsg.StatusMsg_201);
			}
			if (4 == reqdata.getType()) {
				//未审核创客
				makerAccount.setExamineMakerReasonsForOverdue(reqdata.getReasonsForOverdue());
			} else {
				//未开工商户
				makerAccount.setUnOpenStudioReasonsForOverdue(reqdata.getReasonsForOverdue());
			}
			if (makerAccount.updateById()) {
				return smartResult();
			} else {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		} else if (6 == reqdata.getType() || 7 == reqdata.getType()) {
			MakerStudio makerStudio = new MakerStudio().selectById(reqdata.getId());
			if (null ==  makerStudio) {
				return smartResult(StatusMsg.StatusMsg_228);
			}
			if (6 == reqdata.getType()) {
				//未开税户
				makerStudio.setReasonsForOverdue(reqdata.getReasonsForOverdue());
			} else {
				//未开支付宝公户
				makerStudio.setReasonsForUnOpenAlipay(reqdata.getReasonsForOverdue());
			}
			if (makerStudio.updateById()) {
				return smartResult();
			} else {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		} else {
			return SmartResult.fail("请联系IT人员!");
		}
	}


	public SmartResult<CountDetailDto> listUnopenStudioDetail() {
		Date finishDate = DateUtil.nowDate();
		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}
		int studioDays = -commonConfig.getStudioDays();
		Date taxAcctStartDate = DateUtil.addWorkDay(finishDate, studioDays);
		List<CountDetailDto> list = reportMapper.listUnopenStudio(taxAcctStartDate, finishDate);
		return SmartResult.success(list);
	}

	public SmartResult<CountDetailDto> listUnopenTaxAcctDetail() {
		Date finishDate = DateUtil.nowDate();
		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}
		int taxAcctDays = -commonConfig.getTaxAcctDays();
		Date taxAcctStartDate = DateUtil.addWorkDay(finishDate, taxAcctDays);
		List<CountDetailDto> list = reportMapper.listUnopenTaxAcct(taxAcctStartDate, finishDate);
		return SmartResult.success(list);
	}

	public SmartResult<CountDetailDto> listUnfinishCompany() {
		Date finishDate = DateUtil.nowDate();
		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}
		List<CountDetailDto> list = reportMapper.listUnfinishCompany(finishDate);
		return SmartResult.success(list);
	}

	public SmartResult<CountDetailDto> listUnfinishMaker() {
		Date finishDate = DateUtil.nowDate();
		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}
		List<CountDetailDto> list = reportMapper.listUnfinishMaker(finishDate);
		return SmartResult.success(list);
	}

	/**
	 * 查询超过3个工作日且已完成工作室开户的但未开支付宝公户的创客列表，完成工作室开户时间在7月7之后
	 * @param formBean
	 * @return
	 */
	public SmartResult<CountDetailDto> listUnOpenAliPayMaker(BaseSimpleFormBean formBean) {
		Date finishDate = DateUtil.addWorkDay(new Date(), -3);

		Page<CountDetailDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CountDetailDto> list = reportMapper.listUnOpenAliPayMaker(finishDate);

		return SmartResult.ofPage(page);
	}

	public SmartResult<RealtimePendingItemDto> getRealtimePendingItems(int userid) {
		//获取地址
		SystemManager systemManager = new SystemManager().selectOne(Condition.create().eq("managerid", userid));
		if (systemManager == null) return optFailSmartResult();
		String dockingCity = systemManager.getDockingCity();

		Date finishDate = DateUtil.nowDate();

		// 周末,统计上个周五的数据
		if (DateUtil.isWeekend(finishDate)) {
			finishDate = DateUtil.addWorkDay(finishDate, -1);
		}

		// 各种标准天数
		//工商户标准天数 3天
		int studioDays = -commonConfig.getStudioDays();
		//开税户标准天数 7 天
		int taxAcctDays = -commonConfig.getTaxAcctDays();
		//首次交易（未开税户）完成开票标准天数 10天
		int untaxAcctInvoiceDays = -commonConfig.getUntaxAcctInvoiceDays();
		//非首次交易（已开税户）完成开票标准天数  四天
		int taxAcctInvoiceDays = -commonConfig.getTaxAcctInvoiceDays();
		//发票库存不足，可以延长开票天数 5天
		int understockInvoiceAddtionDays = -commonConfig.getUnderstockInvoiceAddtionDays();
		//首次交易（未开税户）完成开票标准天数 + 发票库存不足，可以延长开票天数
		int understockUntaxAcctInvoiceDays = untaxAcctInvoiceDays + understockInvoiceAddtionDays;
		//非首次交易（已开税户）完成开票标准天数 + 发票库存不足，可以延长开票天数
		int understockTaxAcctInvoiceDays = taxAcctInvoiceDays + understockInvoiceAddtionDays;

		// 各种标准开始时间
		Date studioStartDate = DateUtil.addWorkDay(finishDate, studioDays);
		Date taxAcctStartDate = DateUtil.addWorkDay(finishDate, taxAcctDays);
		Date untaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, untaxAcctInvoiceDays);
		Date taxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, taxAcctInvoiceDays);
		Date understockUntaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, understockUntaxAcctInvoiceDays);
		Date understockTaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, understockTaxAcctInvoiceDays);
		//开支付宝公户天数 三个工作日
		Date unOpenAliPayDate = DateUtil.addWorkDay(finishDate, -3);

		// 未开工商户,标准内外
		StatisticCountDto unopenStudioCount = reportMapper.countUnopenStudio(studioStartDate);
		// 未开税户,标准内外
		StatisticCountDto unopenTaxAcctCount = reportMapper.countUnopenTaxAcct(taxAcctStartDate);

		// 普通项目未开票数, 普票待开,专票待开,策略性待开票,标准内未开税户(首次交易)待开数,标准内已开税户(非首次交易)待开数,标准外未开税户(首次交易)待开数,标准外已开税户(非首次交易)待开数
		UnfinishedInvoiceCountDto unfinishedInvoiceCount = reportMapper.countUnfinishedInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate, understockTaxAcctInvoiceStartDate,
				taxAcctInvoiceStartDate, finishDate);
		//  项目未开票数, 普票待开,专票待开,策略性待开票,标准内未开税户(首次交易)待开数,标准内已开税户(非首次交易)待开数,标准外未开税户(首次交易)待开数,标准外已开税户(非首次交易)待开数
		UnfinishedInvoiceCountDto unfinishedTaxerInvoiceCount = reportMapper.countUnfinishedTaxerInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate,
				understockTaxAcctInvoiceStartDate, taxAcctInvoiceStartDate);
		unfinishedInvoiceCount.add(unfinishedTaxerInvoiceCount);

		// 主要取  项目 标准内未开税户(首次交易)待开数,标准外未开税户(首次交易)待开数，标准内已开税户(非首次交易)待开数,,标准外已开税户(非首次交易)待开数
		UnfinishedInvoiceCountDto toBeInvoiceFirstOrNotFirstCount = reportMapper.toBeInvoiceFirstOrNotFirstCount(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate, understockTaxAcctInvoiceStartDate,
				taxAcctInvoiceStartDate);

        //待注销统计
        int pendingCancellation = makerRescissionApplyMapper.countCancellation(2,dockingCity);
        //注销申请待审核的数量
        int applyingCancellation = makerRescissionApplyMapper.countCancellation(1,dockingCity);
        //待审核统计
        List<VerifyingMakerDto> makerDtoList = makerAccountMapper.getVerifyList(1, null, null, 2, new Date(0), new Date(), "", "", null, "",
                null);

        //线下代付统计
        List<CrowdOfflinePayProjectListDto> crowdOfflinePayList = crowdsourceProjectMapper.queryOfflinePayProjectByCondition(new Date(0), new Date(), null, 2);
        List<ProjectJiugeOfflinePayDto> projectJiugeOfflinePayList = projectMapper.getJiugeOfflinePayProjectList("", 15, new Date(0), new Date());

        // 合伙人提现申请中数量
		int partnerWithdrawApplyingCount = partnerWithdrawMapper.countApplyingWithdraws();
		int partnerStudioWithdrawApplyingCount = partnerStudioWithdrawMapper.countApplyingWithdraws();
		//未上传+已过期合同数量
		int contractQuantityNotUploaded = reportMapper.contractQuantityNotUploaded();

		//获取1个月内即将到期的合伙人
		Date expiredate = DateUtil.addMonth(DateUtil.nowDate(), 1);
		List<PartnerExpireDto> partnerExpireDto = partnerAccountMapper.getPendingExpirePartnerList("", "", "", expiredate);
		int numberOfPartnersDue = partnerExpireDto.size();
		//统计招行智能支付异常
		List<CompanyZhaoshangSubLedgerIncomingRecordDto> companyZhaoshang = companyZhaoshangSubLedgerIncomingRecordMapper.list(0, null, 0, null, 2, 0, new Date(0), new Date());
        int smartPaymentException = companyZhaoshang.size();
        //统计代付账目支付失败
		List<TradeRecordBriefDto> tradeRecordBriefDto = tradeRecordMapper.TradeRecordList(null, 1, 4, new Date(0), new Date());
		int accountPaymentFailed = tradeRecordBriefDto.size();
		//统计代付账目手动处理失败
		int manualFailed = 0;
		List<TradeRecordBriefDto> manualProcessingFailed = tradeRecordMapper.TradeRecordList(null, 1, 2, new Date(0), new Date());
		for (TradeRecordBriefDto dto:manualProcessingFailed) {
			if (2 == dto.getTradestate() && (CompanyPayType.isZhaoShangPayType(dto.getPayId()) || CompanyPayType.isPingAnPayType(dto.getPayId()))) {
				//获取交易时间
				Date transactionTime = dto.getTradetime();
				long differTime = DateUtil.differMinute(DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", transactionTime),
						DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
				if (120 < differTime) {
					manualFailed++;
				}
			}
		}

		accountPaymentFailed = accountPaymentFailed+manualFailed;

		//统计智众包交易失败
		List<CrowdsourceTradeRecordDto> crowdsourceTradeRecordDto= crowdsourceTradeRecordMapper.statisticsTradeRecordList();
		int smartCrowdsourcingDealFailed = crowdsourceTradeRecordDto.size();
		//统计发布失败的项目数量
		ProjectListFormBean projectListFormBean = new ProjectListFormBean();
		projectListFormBean.setState(3).setWhetherSupplement(0);
		//待上传完税凭证
		List<TaxClearanceCertificateDto> taxClearanceCertificate = contractorInvoiceMapper.taxClearanceCertificate(null,null,null);
		//智零工成本票待开票
		List<ContractorInvoicefDto> contractorInvoiceList = contractorInvoiceMapper.contractorInvoiceList(null,1,new Date(0),new Date());

		RealtimePendingItemDto dto = new RealtimePendingItemDto();
        dto.setUnfinishUntaxAcctInvoiceUnstandard(unfinishedInvoiceCount.getUnTaxAcctUnstandardCount())
                .setUnfinishTaxAcctInvoiceUnstandard(unfinishedInvoiceCount.getTaxAcctUnstandardCount())
                .setUnfinishStudioUnstandard(unopenStudioCount.getUnstandardCount())
                .setUnfinishTaxAcctUnstandard(unopenTaxAcctCount.getUnstandardCount())
                .setUnfinishCompanyUnstandard(reportMapper.countUnfinishCompanyUnstandard(finishDate))
                .setUnfinishMakerUnstandard(reportMapper.countUnfinishMakerUnstandard(finishDate))
                .setPendingGenInvoice(unfinishedInvoiceCount.getGenCount())
                .setPendingSpeInvoice(unfinishedInvoiceCount.getSpeCount())
                .setPendingStrategyInvoice(unfinishedInvoiceCount.getStrategyCount())
                // 待开票,包含逾期的数量
                .setPendingUntaxAcctInvoice(unfinishedInvoiceCount.getUnTaxAcctStandardCount() + unfinishedInvoiceCount.getUnTaxAcctUnstandardCount())
                .setPendingTaxAcctInvoice(unfinishedInvoiceCount.getTaxAcctStandardCount() + unfinishedInvoiceCount.getTaxAcctUnstandardCount())
                .setPendingCompany(reportMapper.countCompanyVerfiying())
                .setPendingMaker(reportMapper.countMakerVerfiying())
                // 待开工商户和税户,包含逾期的数量
                .setPendingStudio(unopenStudioCount.getStandardCount() + unopenStudioCount.getUnstandardCount())
                .setPendingTaxAcct(unopenTaxAcctCount.getStandardCount() + unopenTaxAcctCount.getUnstandardCount())
                // 待注销
                .setPendingCancellation(pendingCancellation)
                .setApplyingCancellation(applyingCancellation)
                //待审核
                .setPendingExamine(makerDtoList.size())
                .setPendingOfflinePayment(crowdOfflinePayList.size() + projectJiugeOfflinePayList.size())
                .setToBeAllInvoiceCount(reportMapper.toBeAllInvoiceCount())
                .setToBeGeneralInvoiceCount(reportMapper.toBeGeneralInvoiceCount())
                .setToBeSpecialInvoiceCount(reportMapper.toBeSpecialInvoiceCount())
                .setToBeInvoiceFirstCount(toBeInvoiceFirstOrNotFirstCount.getUnTaxAcctStandardCount() + toBeInvoiceFirstOrNotFirstCount.getUnTaxAcctUnstandardCount())
                .setToBeInvoiceNotFirstCount(toBeInvoiceFirstOrNotFirstCount.getTaxAcctStandardCount() + toBeInvoiceFirstOrNotFirstCount.getTaxAcctUnstandardCount())
                .setToBeCrowdSourceInvoiceCount(reportMapper.toBeCrowdSourceInvoiceCount())
                .setToBeCostInvoiceCount(reportMapper.toBeCostInvoiceCount())
                .setToBeTaxerInvoiceCount(reportMapper.toBeTaxerInvoiceCount())
                .setToBePureAgencyInvoiceCount(reportMapper.toBePureAgencyInvoiceCount())
                .setToBeJiaYinInvoiceCount(0)
                .setToBeMergeJiaYinInvoiceCount(0)
                .setToBeReviewedPartnerCount(reportMapper.toBeReviewedPartnerCount())
                .setToBeReviewedCompanyCount(reportMapper.toBeReviewedCompanyCount())
                .setExpiredButNotStoppedCount(reportMapper.expiredButNotStoppedCount())
                .setToBeReviewedTaxerStudioCount(reportMapper.toBeReviewedTaxerStudioCount())
                .setToBePaidTaxerStudioCount(reportMapper.toBePaidTaxerStudioCount())
                .setToBeAnsweredComplaintCount(reportMapper.toBeAnsweredComplaintCount())
                .setAppreciationService(reportMapper.toBeAppreciationServiceCount())
                .setZddWaitInvokeSum(reportMapper.getZddWaitInvokeSum())
                .setCrowdsourceWaitInvokeSum(reportMapper.getCrowdsourceWaitInvokeSum())
                .setTaxerWaitInvokeSum(reportMapper.getTaxerWaitInvokeSum())
                .setGongQingInvoiceMakerSum(reportMapper.getGongQingInvoiceMakerSum())
                .setGongQingInvoiceNaturalSum(reportMapper.getGongQingInvoiceNaturalSum())
                .setGongQingInvoiceMergeSum(reportMapper.getGongQingInvoiceMergeSum())
                .setMemorandumByConditionSum(reportMapper.getMemorandumByConditionSum())
                .setAllServeSum(reportMapper.getAllServeSum())
                .setServiceErrorSum(reportMapper.getServiceErrorSum())
                .setRechargeApplySum(reportMapper.getRechargeApplySum())
				.setEvaluateCount(evaluateMapper.queryEvaluationCount(DateUtil.getPreviousWorkingDay(new Date())))
		        .setPartnerStudioWithdrawApplyingCount(partnerStudioWithdrawApplyingCount)
		        .setPartnerWithdrawApplyingCount(partnerWithdrawApplyingCount)
		        .setUnOpenAliPay(reportMapper.listUnOpenAliPayMaker(unOpenAliPayDate).size())
				//未上传合同数量
				.setContractQuantityNotUploaded(contractQuantityNotUploaded)
				//合伙人到期数量
				.setNumberOfPartnersDue(numberOfPartnersDue)
				//统计支付失败
				.setSmartPaymentException(smartPaymentException)
				.setAccountPaymentFailed(accountPaymentFailed)
				.setSmartCrowdsourcingDealFailed(smartCrowdsourcingDealFailed)
				.setStatisticsReleaseFailedProjects(projectService.getProjectListQuantity(projectListFormBean))
				.setNumberOfRefundsPending(enterpriseRefundMapper.requestRefundList("",1).size())
				.setAcceptance(projectMapper.getProjectBriefList(null, 0, 12, null, null, "",
						0, null, null,null,0).size())
				.setEntrustZhiduoQuantity(entrustmentProjectMapper.getCount(5))
				.setEntrustCrowdsourcingQuantity(entrustmentProjectMapper.getCount(6))
				//返回待审核的签约合同数量
				.setContractAuditNum(companyEntrustFileMapper.getAuditNum()).setNonstandardProjectNum(nonstandardProjectMapper.queryIncompleteNum(userid, systemManager.getRoleid()))
				.setAdminImportCroProjectNum(crowdsourceProjectMapper.getAdminImportCroProjectNum())
				.setTaxClearanceCertificateToBeUploaded(taxClearanceCertificate.size())
				.setSmartGigCostInvoicesToBeInvoiced(contractorInvoiceList.size())
		        .setCompApplyPendingNum(companyApplyMapper.queryPendingNum())
				;


        return SmartResult.success(dto);
    }

	/**
	 收集日报数据

	 @param finishDate
	 */
	public void collectReportStatistic(Date finishDate) {
		if (finishDate == null) {
			finishDate = DateUtil.getYesterday();
		}

		// 周末,不统计
		if (DateUtil.isWeekend(finishDate)) {
			return;
		}

		// 整理发票,标记是否是库存不足.库存不足的,需要增加5天缓冲期
		// 普通发票
//		List<Invoice> unfinishInvoiceList = invoiceMapper.getUnfinishList();
//		unfinishInvoiceList.stream().collect(Collectors.groupingBy(Invoice::getUserid)).forEach((userid, list) -> {
//
//			double genAmount = 0;
//			double speAmount = 0;
//			InvoiceInventory inventory = new InvoiceInventory().selectById(userid);
//			if (inventory != null) {
//				genAmount = inventory.getGenHundredThousand() * 100000 + inventory.getGenTenThousand() * 10000;
//				speAmount = inventory.getSpeHundredThousand() * 100000 + inventory.getSpeTenThousand() * 10000;
//			}
//
//			// 库存不足,标记所有发票记录
//			for (Invoice invoice : list) {
//				boolean understock = false;
//				Integer invoicetype = invoice.getInvoicetype();
//				double amount = invoice.getInvoiceAmount().doubleValue();
//				if (NumberUtil.equals(invoicetype, InvoiceType.GENERAL)) {
//					understock = genAmount < amount;
//				} else if (NumberUtil.equals(invoicetype, InvoiceType.SPECIAL)) {
//					understock = speAmount < amount;
//				}
//				if (understock) {
//					invoice.setUnderstock(Constants.TRUE).updateById();
//				}
//			}
//
//		});

		//  
		List<TaxerInvoice> taxerInvoiceList = taxerInvoiceMapper.getUnfinishList(0);
		taxerInvoiceList.stream().collect(Collectors.groupingBy(TaxerInvoice::getUserid)).forEach((userid, list) -> {
			double genAmount = 0;
			double speAmount = 0;
			InvoiceInventory inventory = new InvoiceInventory().selectById(userid);
			if (inventory != null) {
				genAmount = inventory.getGenHundredThousand() * 100000 + inventory.getGenTenThousand() * 10000;
				speAmount = inventory.getSpeHundredThousand() * 100000 + inventory.getSpeTenThousand() * 10000;
			}
			for (TaxerInvoice taxerInvoice : list) {
				boolean understock = false;
				Integer invoicetype = taxerInvoice.getInvoiceType();
				double amount = taxerInvoice.getAmount().doubleValue();
				if (NumberUtil.equals(invoicetype, InvoiceType.GENERAL)) {
					understock = genAmount < amount;
				} else if (NumberUtil.equals(invoicetype, InvoiceType.SPECIAL)) {
					understock = speAmount < amount;
				}
				if (understock) {
					taxerInvoice.setUnderstock(Constants.TRUE).updateById();
				}
			}
		});

		// 各种标准天数
		int studioDays = -commonConfig.getStudioDays();
		int taxAcctDays = -commonConfig.getTaxAcctDays();
		int untaxAcctInvoiceDays = -commonConfig.getUntaxAcctInvoiceDays();
		int taxAcctInvoiceDays = -commonConfig.getTaxAcctInvoiceDays();
		int understockInvoiceAddtionDays = -commonConfig.getUnderstockInvoiceAddtionDays();
		int understockUntaxAcctInvoiceDays = untaxAcctInvoiceDays + understockInvoiceAddtionDays;
		int understockTaxAcctInvoiceDays = taxAcctInvoiceDays + understockInvoiceAddtionDays;

		// 各种标准开始时间
		Date studioStartDate = DateUtil.addWorkDay(finishDate, studioDays);
		Date taxAcctStartDate = DateUtil.addWorkDay(finishDate, taxAcctDays);
		Date untaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, untaxAcctInvoiceDays);
		Date taxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, taxAcctInvoiceDays);
		Date understockUntaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, understockUntaxAcctInvoiceDays);
		Date understockTaxAcctInvoiceStartDate = DateUtil.addWorkDay(finishDate, understockTaxAcctInvoiceDays);

		// 今日已开工商户,标准内外,港澳台
		StatisticCountDto studioCount = reportMapper.countOpenStudio(studioStartDate, finishDate);
		// 未开工商户,标准内外
		StatisticCountDto unopenStudioCount = reportMapper.countUnopenStudio(studioStartDate);
		// 今日已开税户,标准内外,港澳台
		StatisticCountDto taxAcctCount = reportMapper.countOpenTaxAcct(taxAcctStartDate, finishDate);
		// 未开税户,标准内外
		StatisticCountDto unopenTaxAcctCount = reportMapper.countUnopenTaxAcct(taxAcctStartDate);

		// 普通项目开票数, 总数,标准内外
//		StatisticCountDto invoiceCount = reportMapper.countFinishedInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate, understockTaxAcctInvoiceStartDate, taxAcctInvoiceStartDate,
//				finishDate);
		//  项目开票数,总数,标准内外
		StatisticCountDto invoiceCount = reportMapper.countFinishedTaxerInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate, understockTaxAcctInvoiceStartDate,
				taxAcctInvoiceStartDate, finishDate);
//		invoiceCount.add(taxerInvoiceCount);

		// 普通项目未开票数, 普票待开,专票待开,策略性待开票,标准内未开税户(首次交易)待开数,标准内已开税户(非首次交易)待开数,标准外未开税户(首次交易)待开数,标准外已开税户(非首次交易)待开数
//		UnfinishedInvoiceCountDto unfinishedInvoiceCount = reportMapper.countUnfinishedInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate, understockTaxAcctInvoiceStartDate,
//				taxAcctInvoiceStartDate, finishDate);
		//  项目未开票数, 普票待开,专票待开,策略性待开票,标准内未开税户(首次交易)待开数,标准内已开税户(非首次交易)待开数,标准外未开税户(首次交易)待开数,标准外已开税户(非首次交易)待开数
		UnfinishedInvoiceCountDto unfinishedInvoiceCount = reportMapper.countUnfinishedTaxerInvoice(understockUntaxAcctInvoiceStartDate, untaxAcctInvoiceStartDate,
				understockTaxAcctInvoiceStartDate, taxAcctInvoiceStartDate);
//		unfinishedInvoiceCount.add(unfinishedTaxerInvoiceCount);

		FinishedInventoryCountDto inventoryCount = reportMapper.countInventory(finishDate);
		int unfinishCompanyUnstandard = reportMapper.countUnfinishCompanyUnstandard(finishDate);
		int unfinishMakerUnstandard = reportMapper.countUnfinishMakerUnstandard(finishDate);

		DailyReport report = new DailyReport().setDate(finishDate)
				.setStudioStandard(studioCount.getStandardCount())
				.setStudioUnstandard(studioCount.getUnstandardCount())
				.setStudioHktw(studioCount.getHktwCount())
				.setTaxAcctStandard(taxAcctCount.getStandardCount())
				.setTaxAcctUnstandard(taxAcctCount.getUnstandardCount())
				.setTaxAcctHktw(taxAcctCount.getHktwCount())
				.setInvoiceTotal(invoiceCount.getTotalCount())
				.setGenTenThousand(inventoryCount.getGenTenThousand())
				.setGenHundredThousand(inventoryCount.getGenHundredThousand())
				.setSpeTenThousand(inventoryCount.getSpeTenThousand())
				.setSpeHundredThousand(inventoryCount.getSpeHundredThousand())
				.setInvoiceStandard(invoiceCount.getStandardCount())
				.setInvoiceUnstandard(invoiceCount.getUnstandardCount())
				.setVerifyCompany(reportMapper.countHandleCompanyVerify(finishDate))
				.setVerifyMaker(reportMapper.countHandleMakerVerify(finishDate))
				.setHandleMaker(reportMapper.countHandleMakerRescissionApply(finishDate))
				.setFinishMaker(reportMapper.countFinishMakerRescissionApply(finishDate))
				.setUnfinishUntaxAcctInvoiceUnstandard(unfinishedInvoiceCount.getUnTaxAcctUnstandardCount())
				.setUnfinishTaxAcctInvoiceUnstandard(unfinishedInvoiceCount.getTaxAcctUnstandardCount())
				.setUnfinishStudioUnstandard(unopenStudioCount.getUnstandardCount())
				.setUnfinishTaxAcctUnstandard(unopenTaxAcctCount.getUnstandardCount())
				.setUnfinishCompanyUnstandard(unfinishCompanyUnstandard)
				.setUnfinishMakerUnstandard(unfinishMakerUnstandard)
				.setPendingGenInvoice(unfinishedInvoiceCount.getGenCount())
				.setPendingSpeInvoice(unfinishedInvoiceCount.getSpeCount())
				.setPendingStrategyInvoice(unfinishedInvoiceCount.getStrategyCount())
				.setPendingUntaxAcctInvoice(unfinishedInvoiceCount.getUnTaxAcctStandardCount() + unfinishedInvoiceCount.getUnTaxAcctUnstandardCount())
				.setPendingTaxAcctInvoice(unfinishedInvoiceCount.getTaxAcctStandardCount() + unfinishedInvoiceCount.getTaxAcctUnstandardCount())
				.setPendingCompany(reportMapper.countCompanyVerfiying())
				.setPendingMaker(reportMapper.countMakerVerfiying())
				.setPendingStudio(unopenStudioCount.getStandardCount() + unopenStudioCount.getUnstandardCount())
				.setPendingTaxAcct(unopenTaxAcctCount.getStandardCount() + unopenTaxAcctCount.getUnstandardCount());

        report.insert();

    }

    //获取企业交易状态统计数量
	public SmartResult companyTradeQuantity(BaseSimpleFormBean formBean){
		CompanyTradeFlagDto companyTradeQuantity = reportMapper.companyTradeQuantity();
		if(companyTradeQuantity == null){
			companyTradeQuantity = new CompanyTradeFlagDto().setTradeFlagNum0(0).setTradeFlagNum1(0).setTradeFlagNum2(0);
		}
		return SmartResult.success(companyTradeQuantity);
	}
}
